<?php

namespace app\admin\model;

use think\Db;
use think\Model;

class Tag extends Model
{
    protected $table = 'petct_tag';

    /**
     * 获取Tag信息
     * @param $limit
     * @param $where
     * @return array
     */
    public function getTagname($limit, $where)
    {
        try {

            $res = $this->where($where)
                ->order('id', 'desc')->paginate($limit);

        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $res, 'ok');
    }

    /**
     * 增加Tag
     * @param $params
     * @return array
     */
    public function addTag($params)
    {
        try {

            $where = [
                'tagname' => $params['tagname']
            ];
            $flag = $this->where($where)->count();
            if ($flag) {
                return modelReMsg(-2, '', 'Tag已经存在');
            }

            $params['add_time'] = date('Y-m-d H:i:s');
            $params['update_time'] = date('Y-m-d H:i:s');
            $params['status'] = 1;

            $this->insert($params);
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '添加成功');
    }

    /**
     * 根据id获取Tag信息
     * @param $id
     * @return array
     */
    public function getTagById($id)
    {
        try {

            $info = $this->where('id', $id)->findOrEmpty()->toArray();
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $info, 'ok');
    }
    /**
     * 根据tagname获取Tag信息
     * @param $tagname
     * @return array
     */
    public function getTagByTagname($tagname)
    {
        try {

            $info = $this->where('tagname', $tagname)->findOrEmpty()->toArray();
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $info, 'ok');
    }

    /**
     * 编辑Tag
     * @param $params
     * @return array
     */
    public function editTag($params)
    {
        try {

            $has = $this->where('tagname', $params['tagname'])
                ->where('id', '<>', $params['id'])
                ->findOrEmpty()->toArray();

            if (!empty($has)) {
                return modelReMsg(-2, '', 'Tag已经存在');
            }
            $params['update_time'] = date('Y-m-d H:i:s');

            $this->save($params, ['id' => $params['id']]);
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '编辑成功');
    }

    /**
     * 删除栏目
     * @param $id
     * @return array
     */
    public function delTag($id)
    {
        try {

            $this->where('id', $id)->delete();
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '删除成功');
    }
}